import CreateModal from '@/pages/System/Emp/components/CreateModal';
import UpdateModal from '@/pages/System/Emp/components/UpdateModal';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography } from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {deleteEmpByIdUsingDelete, selectEmpPageUsingGet} from "@/services/tlias-backend/empController";
import { Popconfirm } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import {selectClassIdAndNameUsingGet} from "@/services/tlias-backend/userController";
import {selectDeptIdAndNameUsingGet} from "@/services/tlias-backend/deptController";

/**
 * 用户管理页面
 *
 * @constructor
 */
const UserAdminPage: React.FC = () => {
  // 是否显示新建窗口
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  // 是否显示更新窗口
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  // 当前用户点击的数据
  const [currentRow, setCurrentRow] = useState<API.User>();

  const [depts, setDepts] = useState<{ id: number, name: string }[]>([]);
  useEffect(() => {
    // 获取教师数据
    const fetchDept = async () => {
      const result = await selectDeptIdAndNameUsingGet();
      if (result.code === 200) {
        setDepts(result.data || [] as any);
      }
    };
    fetchDept();
  }, []);

  /**
   * 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.Emp) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteEmpByIdUsingDelete({
        id: row.id as any,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<API.EmpVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueEnum: {
        1: {
          text: '男',
        },
        2: {
          text: '女',
        },
      },
    },
    {
      title: '部门ID',
      dataIndex: 'deptId',
      valueType: 'text',
      hideInSearch: true,
      render: (deptId: number): string => {
        // 查找班主任名称
        const item = depts.find(item => item.id === deptId);
        return item ? item.name : '未知部门';
      },
    },
    {
      title: '头像',
      dataIndex: 'image',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '职位',
      dataIndex: 'job',
      valueEnum: {
        1: {
          text: '班主任',
        },
        2: {
          text: '讲师',
        },
        3: {
          text: '学工主管',
        },
        4: {
          text: '教研主管',
        },
        5: {
          text: '咨询师',
        },
      },
    },
    {
      title: '入职时间',
      dataIndex: 'entrydate',
      valueType: 'date',
      hideInSearch: true,
      // hideInForm: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '修改时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size="middle">
          <Typography.Link
            onClick={() => {
              setCurrentRow(record);
              setUpdateModalVisible(true);
            }}
          >
            修改
          </Typography.Link>
          <Popconfirm
            title="确定删除此项吗?"
            description="删除后无法恢复，请谨慎操作。"
            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
            onConfirm={() => handleDelete(record)}
            okText="确认"
            cancelText="取消"
          >
            <Typography.Link type="danger">
              删除
            </Typography.Link>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.EmpVO>
        // headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}

        request={async (params , sort, filter) => {
          const sortBy = Object.keys(sort)?.[0];
          const isAsc = sort?.[sortBy] ?? undefined;
          // const initSearchParams = {
          //   page: 1,
          //   pageSize: 10,
          // };

          const { data, code } = await selectEmpPageUsingGet({
            ...params,
            sortBy,
            isAsc,
            ...filter,
          } as API.selectEmpPageUsingGETParams);

          return {
            success: code === 200,
            data: data?.list || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />

      <CreateModal
        visible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      <UpdateModal
        visible={updateModalVisible}
        columns={columns}
        oldData={currentRow}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default UserAdminPage;
